package com.tractorframework.core;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;

class ViewChange implements ViewGroup.OnHierarchyChangeListener{
	
	private IViewChangeListener listener;
	
	private View root;
	
	public ViewChange(Activity root)
	{
		this.root = root.findViewById(android.R.id.content);
		this.root.post(new Runnable() {
			
			@Override
			public void run() {
				createDescendentsHierarchyListenerAndFireViewAdded(ViewChange.this.root);
			}
		});
	}
	
	private void getDescendents(List<View> list, View parent)
	{
		if(!(parent instanceof ViewGroup))
		{
			return;
		}
		ViewGroup group = (ViewGroup)parent;
		int count = group.getChildCount();
		for(int i = 0; i < count; i++)
		{
			View child = group.getChildAt(i);
			list.add(child);
			getDescendents(list, child);
		}
	}
	
	private void createViewHierarchyListener(View parent)
	{
		if(parent instanceof ViewGroup)
		{
			ViewGroup group = (ViewGroup)parent;
			group.setOnHierarchyChangeListener(this);
		}
	}
	
	private void createDescendentsHierarchyListenerAndFireViewAdded(View parent)
	{
		 List<View> list = new ArrayList<View>();
		 getDescendents(list, parent);
		 for(View view : list)
		 {
			 createViewHierarchyListener(view);
			 fireViewAdded(view);
		 }
	}
	
	private void removeDescendentsHierarchyListenerAndFireViewAdded(View parent)
	{
		 List<View> list = new ArrayList<View>();
		 getDescendents(list, parent);
		 for(View view : list)
		 {
			 removeViewHierarchyListener(view);
			 fireViewRemoved(view);
		 }
	}
	
	private void removeViewHierarchyListener(View parent)
	{
		if(parent instanceof ViewGroup)
		{
			ViewGroup group = (ViewGroup)parent;
			group.setOnHierarchyChangeListener(null);
		}
	}

	public IViewChangeListener getListener() {
		return listener;
	}

	public void setListener(IViewChangeListener listener) {
		this.listener = listener;
	}
	
	public void dispose()
	{
		removeDescendentsHierarchyListenerAndFireViewAdded(this.root);
		listener = null;
	}

	@Override
	public void onChildViewAdded(View parent, View child) {
		createDescendentsHierarchyListenerAndFireViewAdded(child);
		createViewHierarchyListener(child);
		fireViewAdded(child);
	}
	
	
	@Override
	public void onChildViewRemoved(View parent, View child) {
		removeDescendentsHierarchyListenerAndFireViewAdded(child);
		removeViewHierarchyListener(child);
		fireViewRemoved(child);
	}
	
	private void fireViewAdded(View child)
	{
		if(listener != null)
		{
			listener.onViewAdded(child.getId(), child);
		}
	}
	
	private void fireViewRemoved(View child)
	{
		if(listener != null)
		{
			listener.onViewRemoved(child.getId(), child);
		}
	}

}
